/*******************************************************************/
/* @ All Rights Reserved Copyright (C) 2014 broada,Co.,Ltd.        */
/*                                                                 */
/*  NAME      = rtcp_core.c                                        */
/*  NOTE      =                                                    */
/*  DATE      = 2015/07/20 by songbb                               */
/*******************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>
#include <sys/types.h>

#include "frcomm.h"
#include "frstr.h"
#include "frhash2.h"
#include "frmem.h"
#include "frlog.h"
#include "frsutl.h"

#include "conntrack.h"
#include "frct_comm.h"
#include "frversion.h"

#include "rtcp_comm.h"
#include "rtcp_core.h"
#include "rtcp_header.h"
#include "rtcp_packet.h"

#if APM_RTCP_DBG
/* 模块全局变量：出错的包的个数 */
FR_STATIC unsigned long long g_ull_rtcp_error_nums = 0LL;
#endif

/*******************************************************************************
*  FUNC     :  累计未正确解析的包个数
*  ARGS     :  *p_st_sess                           (RTCP私有的session)
*  RTN      :
*  NOTE     :
*******************************************************************************/
FR_STATIC void __rtcp_add_error_nums(L7session_rtcp *p_st_sess)
{
#if APM_RTCP_DBG
    g_ull_rtcp_error_nums++;
#endif
    if (p_st_sess != NULL)
        p_st_sess->ull_error_nums++;
    return;
}

/*******************************************************************************
*  FUNC     :  初始化RTCP包的信息
*  ARGS     :  *p_st_rtcp_packet                     (RTCP数据包)
*  RTN      :  0                                    (FR_SUCC)
*              1                                    (FR_FAIL)
*  NOTE     :
*******************************************************************************/
int __rtcp_init_packet(L7_rtcp_packet *p_st_rtcp_packet)
{
    RTCP_PRINT_INFO("init rtcp_packet...\n");
    if (p_st_rtcp_packet == NULL)
        return FR_SUCC;

    p_st_rtcp_packet->i_is_req = APM_RTCP_FLAG_UNSET;
    bytebuff_free(&(p_st_rtcp_packet->p_st_packet));
    if ((p_st_rtcp_packet->p_st_packet = bytebuff_creat()) == NULL)
        return FR_FAIL;

    return FR_SUCC;
}

/*******************************************************************************
*  FUNC     :  预备需要解析的数据
*  ARGS     :  *p_st_sess                           (RTCP私有的session)
*           :  *p_st_data_in                        (协议分析入力数据)
*           :  *p_st_rtcp_packet                     (RTCP数据包)
*  RTN      :  0                                    (FR_SUCC)
*              1                                    (FR_FAIL)
*  NOTE     :
*******************************************************************************/
int __rtcp_packet_prepare(L7session_rtcp *p_st_sess
                        , Apm_packet *p_st_data_in
                        , L7_rtcp_packet *p_st_rtcp_packet)
{
    if (p_st_data_in->i_direction == FR_DIRECT_UNKNOWN)
        goto error;

    if (__rtcp_init_packet(p_st_rtcp_packet) != FR_SUCC)
        goto error;

    if (bytebuff_add(p_st_rtcp_packet->p_st_packet, p_st_data_in->p_payload, p_st_data_in->ui_payload_len) != FR_SUCC)
        goto error;
    p_st_rtcp_packet->st_timestamp_first = p_st_data_in->st_timestamp;
    p_st_rtcp_packet->st_timestamp_last = p_st_data_in->st_timestamp;
    p_st_rtcp_packet->i_is_req = p_st_data_in->i_direction == FR_DIRECT_CLIENT2SRV ? FR_YES : FR_NO;

    return FR_SUCC;
error:
    bytebuff_free(&(p_st_rtcp_packet->p_st_packet));
    return FR_FAIL;
}


/*******************************************************************************
*  FUNC     :  RTCP Session初始化
*  ARGS     :  *p_st_session                            (L7层session信息)
*  RTN      :  0                                        (FR_SUCC)
*              1                                        (FR_FAIL)
*  NOTE     :
*******************************************************************************/
FR_STATIC int __rtcp_private_session_init(L7_session *p_st_session)
{
    RTCP_PRINT_INFO("session init\n");
    L7session_rtcp_private *p_st_rtcp_private = NULL;      // RTCP的私有信息
    L7session_rtcp *p_st_rtcp_sess = NULL;                 // RTCP的私有session信息
    L7_rtcp_packet *p_st_rtcp_packet = NULL;               // RTCP格式的packet包

    // 1. 初始化RTCP的私有session信息
    if ((p_st_rtcp_sess = (L7session_rtcp *) frmalloc(sizeof(L7session_rtcp))) == NULL)
    {
        RTCP_MALLOCK_ERR;
        goto error;
    }
    memset(p_st_rtcp_sess, 0x00, sizeof(L7session_rtcp));

#if APM_RTCP_DBG
    p_st_rtcp_sess->st_timestamp.tv_sec = 0L;
    p_st_rtcp_sess->st_timestamp.tv_usec = 0L;
#endif

    // 2. 初始化RTCP格式的packet包
    if ((p_st_rtcp_packet = (L7_rtcp_packet *) frmalloc(sizeof(L7_rtcp_packet))) == NULL)
    {
        RTCP_MALLOCK_ERR;
        goto error;
    }
    memset(p_st_rtcp_packet, 0x00, sizeof(L7_rtcp_packet));
    if (__rtcp_init_packet(p_st_rtcp_packet) != FR_SUCC)
        goto error;

    // 3. 创建和初始化RTCP的私有信息
    if ((p_st_rtcp_private = (L7session_rtcp_private *) frmalloc(sizeof(L7session_rtcp_private))) == NULL)
    {
        RTCP_MALLOCK_ERR;
        goto error;
    }
    memset(p_st_rtcp_private, 0x00, sizeof(L7session_rtcp_private));
    p_st_rtcp_private->p_st_sess = p_st_rtcp_sess;
    p_st_rtcp_private->p_st_rtcp_packet = p_st_rtcp_packet;
    p_st_rtcp_private->p_st_session = p_st_session;

    // 5. 设置L7_session的p_session_private信息
    frct_set_session_private(p_st_session, (void *)p_st_rtcp_private);

    return FR_SUCC;
error:
    rtcp_free((void **) &p_st_rtcp_private);
    return FR_FAIL;
}

/*******************************************************************************
*  FUNC     :  分析数据方向
*  ARGS     :  *p_st_data_in                            (协议分析入力数据)
*  RTN      :  0x00                                     (FR_DIRECT_UNKNOWN)
*              0x02                                     (FR_DIRECT_SRV2CLIENT)
*              0x03                                     (FR_DIRECT_CLIENT2SRV)
*  NOTE     :
*******************************************************************************/
FR_STATIC int __rtcp_analyze_direct(Apm_packet *p_st_data_in)
{
    RTCP_PRINT_INFO("__rtcp_analyze_direct\n");
    RTCP_PRINT_FATAL("assume client to server\n");
    return FR_DIRECT_CLIENT2SRV;
}

/*******************************************************************************
*  FUNC     :  判断当前数据链路是否是RTCP协议的
*  ARGS     :  *p_st_conn                           (ct信息)
*           :  *p_st_data_in                        (协议分析入力数据)
*  RTN      :  参照module.h中APM_L7_IS_的定义
*  NOTE     :
*******************************************************************************/
int rtcp_detect(Conntrack *p_st_conn
            , Apm_packet *p_st_data_in)
{
    RTCP_PRINT_INFO("rtcp_detect\n");
    int i_analyzed_direct = 0;
    L7_session *p_st_session = frct_get_session(p_st_conn);
    L7session_rtcp_private *p_st_session_private = frct_get_session_private(p_st_session);

#if APM_RTCP_DBG
    char arr_ip_src[56], arr_ip_dst[56];
    snprintf(arr_ip_src, sizeof(arr_ip_src), "%s", int_ntoa(p_st_data_in->src_ip));
    snprintf(arr_ip_dst, sizeof(arr_ip_src), "%s", int_ntoa(p_st_data_in->dst_ip));
    RTCP_PRINT_TIMEVAL("PacketIn", p_st_data_in->st_timestamp);
    RTCP_PRINT_DBG("Src:[%s:%d] Dest:[%s:%d] Length:[%u]\n", arr_ip_src, p_st_data_in->src_port, arr_ip_dst, p_st_data_in->dst_port, p_st_data_in->ui_payload_len);
#endif

    int i_ret;
    i_ret = rtcp_header_detect(p_st_data_in->p_payload, p_st_data_in->ui_payload_len);
    if (i_ret == APM_L7_IS_YES && p_st_session_private == NULL)
    {
        // 设置方向
        if (p_st_data_in->i_direction == FR_DIRECT_UNKNOWN || frct_get_direct_known(p_st_conn) == FR_DIRECT_UNKNOWN)
        {
            i_analyzed_direct = __rtcp_analyze_direct(p_st_data_in);
            if (i_analyzed_direct == FR_DIRECT_CLIENT2SRV)
            {
                if (frcap_set_cs_srv(p_st_conn, p_st_data_in->dst_ip, p_st_data_in->dst_port) != FR_SUCC)
                    return APM_L7_IS_UNKNOWN;
            }
            else if (i_analyzed_direct == FR_DIRECT_SRV2CLIENT)
            {
                if (frcap_set_cs_srv(p_st_conn, p_st_data_in->src_ip, p_st_data_in->src_port) != FR_SUCC)
                    return APM_L7_IS_UNKNOWN;
            }
            else
            {
                RTCP_PRINT_EMERG("Can not analyze direction\n");
                return APM_L7_IS_UNKNOWN;
            }
        }

        // 初始化RTCP的private session数据
        if (__rtcp_private_session_init(p_st_session) != FR_SUCC)
            return APM_L7_IS_UNKNOWN;

        p_st_session_private = frct_get_session_private(p_st_session);
        if (p_st_session_private == NULL || p_st_session_private->p_st_sess == NULL)
            return APM_L7_IS_UNKNOWN;

        // 设置session uuid
        fruuid(p_st_session->arr_session_id);

        //frct_set_statIp(p_st_conn, p_st_data_in->src_ip, 50005, p_st_data_in->dst_ip, 50005);
        frct_set_statIp(p_st_conn, 50005, 50005);
    }

    if (i_ret == APM_L7_IS_UNKNOWN)
        RTCP_PRINT_ERR("detect unknown\n\n");
    else
        RTCP_PRINT_ERR("detect yes\n\n");

    return i_ret;
}

/*******************************************************************************
*  FUNC     :  RTCP协议解析
*  ARGS     :  *p_st_conn                           (ct信息)
*           :  *p_st_data_in                        (协议分析入力数据)
*           :  *p_st_hash_report                    (保存Frreport_data)
*  RTN      :  参照module.h中APM_L7_ANALYZE_的定义
*  NOTE     :
*******************************************************************************/
int rtcp_analyze(Conntrack *p_st_conn
                , Apm_packet *p_st_data_in
                , Frhash_header *p_st_hash_report)
{
    RTCP_PRINT_INFO("rtcp_analyze\n");
    L7_session *p_st_session = frct_get_session(p_st_conn);
    L7session_rtcp_private *p_st_session_private = NULL;
    L7session_rtcp *p_st_sess = NULL;
    L7_rtcp_packet *p_st_rtcp_packet = NULL;
    char arr_ip_src[56], arr_ip_dst[56];
    snprintf(arr_ip_src, sizeof(arr_ip_src), "%s", int_ntoa(p_st_data_in->src_ip));
    snprintf(arr_ip_dst, sizeof(arr_ip_src), "%s", int_ntoa(p_st_data_in->dst_ip));

    RTCP_PRINT_TIMEVAL("PacketIn", p_st_data_in->st_timestamp);
    RTCP_PRINT_DBG("Src:[%s:%d] Dest:[%s:%d] SessionID:[%s]\n", arr_ip_src, p_st_data_in->src_port, arr_ip_dst, p_st_data_in->dst_port, p_st_session->arr_session_id);

    /*
    * 如果入力p_st_data_in是FIN包, 说明本次connection结束,
    * 释放本次session信息. 如果入力p_st_data_in是SYN包,说明新的
    * connection开始了, 释放上次可能残留的session信息
    */
    if (p_st_data_in->em_analyz_cmd == FRANALYZ_CMD_FIN || p_st_data_in->em_analyz_cmd == FRANALYZ_CMD_SYN)
    {
        if (p_st_data_in->em_analyz_cmd == FRANALYZ_CMD_SYN)
            RTCP_PRINT_INFO("SYN PACKET\n");
        else if (p_st_data_in->em_analyz_cmd == FRANALYZ_CMD_FIN)
            RTCP_PRINT_INFO("FIN PACKET\n");
        if (p_st_session->p_session_private != NULL)
        {
            rtcp_session_destroy(p_st_session->p_session_private);
            p_st_session->p_session_private = NULL;
        }
        RTCP_PRINT("### i_analyze_ret:[%d]\n\n", APM_L7_ANALYZE_SUCC);
        return APM_L7_ANALYZE_SUCC;
    }

    // 本次链路的第一个有效packet包,创建链路
    if (p_st_session->p_session_private == NULL)
    {
        // 初始化RTCP的session数据
        if (__rtcp_private_session_init(p_st_session) != FR_SUCC)
            goto rtcp_analyze_fail;

        // 设置session uuid
        fruuid(p_st_session->arr_session_id);
    }

    // 打印方向
    switch (p_st_data_in->i_direction)
    {
        case FR_DIRECT_CLIENT2SRV:
            RTCP_PRINT("client["KLIMEGREEN"%s:%d"RESET"] to server["KLIMEGREEN"%s:%d"RESET"] ["KYELLOW"%d"RESET"] ->>>>>>>>>>>>>>>>>>>>>>>\n",
                      arr_ip_src,
                      p_st_data_in->src_port,
                      arr_ip_dst,
                      p_st_data_in->dst_port,
                      p_st_data_in->ui_payload_len);
            break;
        case FR_DIRECT_SRV2CLIENT:
            RTCP_PRINT("server["KLIMEGREEN"%s:%d"RESET"] to client["KLIMEGREEN"%s:%d"RESET"] ["KYELLOW"%d"RESET"] <<<<<<<<<<<<<<<<<<<<<<<-\n",
                      arr_ip_src,
                      p_st_data_in->src_port,
                      arr_ip_dst,
                      p_st_data_in->dst_port,
                      p_st_data_in->ui_payload_len);
            break;
        default:
            RTCP_PRINT("unknown direction, src["KLIMEGREEN"%s:%d"RESET"], dest["KLIMEGREEN"%s:%d"RESET"]\n",
                      arr_ip_src,
                      p_st_data_in->src_port,
                      arr_ip_dst,
                      p_st_data_in->dst_port);
            goto rtcp_analyze_fail;
    }

    p_st_session_private = frct_get_session_private(p_st_session);
    p_st_sess = p_st_session_private->p_st_sess;
    p_st_rtcp_packet = p_st_session_private->p_st_rtcp_packet;

    if (__rtcp_packet_prepare(p_st_sess, p_st_data_in, p_st_rtcp_packet) != FR_SUCC)
        goto rtcp_analyze_fail;

    if (rtcp_analyze_packet(p_st_conn, p_st_sess, p_st_rtcp_packet, p_st_hash_report) != FR_SUCC)
        goto rtcp_analyze_fail;

    RTCP_PRINT("### i_analyze_ret success:[%d]\n\n", APM_L7_ANALYZE_SUCC);
    return APM_L7_ANALYZE_SUCC;
rtcp_analyze_fail:
    __rtcp_add_error_nums(p_st_sess);
    RTCP_PRINT_PACKET("error packet", p_st_rtcp_packet);
    __rtcp_init_packet(p_st_rtcp_packet);

    RTCP_PRINT_EMERG("### i_analyze_ret fail:[%d]\n\n", APM_L7_ANALYZE_FAIL);
    return APM_L7_ANALYZE_FAIL;
}

/*******************************************************************************
*  FUNC     :  释放 L7session_rtcp
*  ARGS     :  **pp_st_session              (L7session_rtcp)
*  RTN      :  void
*  NOTE     :
*******************************************************************************/
FR_STATIC void __rtcp_destroy_session(L7session_rtcp **pp_st_session)
{
    if (pp_st_session == NULL || *pp_st_session == NULL)
        return;

    rtcp_free((void **) pp_st_session);
    return;
}

/*******************************************************************************
*  FUNC     :  释放 L7_rtcp_packet
*  ARGS     :  **pp_st_rtcp_packet              (L7_rtcp_packet)
*  RTN      :  void
*  NOTE     :
*******************************************************************************/
FR_STATIC void __rtcp_destroy_packet(L7_rtcp_packet **pp_st_rtcp_packet)
{
    if (pp_st_rtcp_packet == NULL || *pp_st_rtcp_packet == NULL)
        return;

    L7_rtcp_packet *p_st_rtcp_packet = *pp_st_rtcp_packet;
    bytebuff_free(&(p_st_rtcp_packet->p_st_packet));
    rtcp_free((void **) pp_st_rtcp_packet);
    return;
}

/*******************************************************************************
*  FUNC     :  释放RTCP private数据
*  ARGS     :  *p_st_session_private_in                 (RTCP的私有信息)
*  RTN      :  0                                        (FR_SUCC)
*              1                                        (FR_FAIL)
*  NOTE     :
*******************************************************************************/
int rtcp_session_destroy(void *p_st_session_private_in)
{
    RTCP_PRINT(KBLUE "\nrtcp_session_destroy run\n" RESET);
    if (p_st_session_private_in == NULL)
        return FR_SUCC;

    L7session_rtcp_private *p_st_private = (L7session_rtcp_private *) p_st_session_private_in;

    __rtcp_destroy_session(&(p_st_private->p_st_sess));

    __rtcp_destroy_packet(&(p_st_private->p_st_rtcp_packet));

    rtcp_free((void **) &p_st_private);

    RTCP_PRINT_INFO("leave rtcp_session_destroy\n");
    return FR_SUCC;
}
